package com.pms.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * 收费模板前端控制器
 * 1)  收费模板 不设删除功能
 * </p>
 *
 * @author ASUS_B
 * @since 2017-11-07
 */
@RestController
@RequestMapping("/chargeTemplateBase")
@Api(value="收费模板管理",description = "收费模板管理相关接口")
public class ChargeTemplateController extends BaseController {
    @Autowired
    IChargeTemplateService chargeTemplateService;
    @Autowired
    IChargeValueService chargeValueService;
    @Autowired
    private IEstateAgencyService estateAgencyService;
    @Autowired
    IChargeNameService chargeNameService;
    @Autowired
    private IUnitHouseService unitHouseService;

    @ApiOperation(value = "分页查询收费模板")
    @RequestMapping(value = "/readPage", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "请求条数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageNum", value = "请求页数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "communityId", value = "社区id", required = false, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name="agencyId",value="物业机构id",required = false,dataType = "long",paramType="form"),
    })
    public R readPage(Integer pageSize, Integer pageNum, Long communityId, Integer chargeType, Long agencyId) {
        if (null == pageNum || pageNum < 1) {
            pageNum = 1;
        }
        if (null == pageSize || pageSize < 1) {
            pageSize = 10;
        }
        Page<ChargeTemplate> page = new Page<ChargeTemplate>(pageNum, pageSize);
        Wrapper<ChargeTemplate> wrapper = new EntityWrapper<ChargeTemplate>();
        if(null!=agencyId){
            wrapper.eq("agency_id",agencyId);
        }
        if(null!=communityId){
            wrapper.eq("community_id", communityId);
        }
        Page<ChargeTemplate> returnPage = chargeTemplateService.selectPage(page, wrapper);
        return R.ok().put("data", returnPage).putMpPageDescription().putDescription(ChargeTemplate.class);
    }

    @ApiOperation(value = "查询收费模板")
    @RequestMapping(value = "/readList", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "communityId", value = "社区id", required = true, dataType = "long", paramType = "form"),
    })
    public R readList(Long communityId) {
        Wrapper<ChargeTemplate> wrapper = new EntityWrapper<ChargeTemplate>().eq("community_id", communityId);
        List<ChargeTemplate> returnPage = chargeTemplateService.selectList(wrapper);
        return R.ok().put("data", returnPage).putDescription(ChargeTemplate.class);
    }

    @ApiOperation(value = "查询收费模板详情")
    @RequestMapping(value = "/readInfo", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "chargeTemplateId", value = "收费模板id", required = true, dataType = "long", paramType = "form"),
    })
    public R readInfo(Long chargeTemplateId) {
        parameterIsNull(chargeTemplateId, "请选择收费模板");
        ChargeTemplate chargeTemplate = chargeTemplateService.selectChargeTemplateInfo (chargeTemplateId);
        return R.ok().put("data", chargeTemplate).putDescription(ChargeTemplate.class).putDescription(ChargeValue.class);
    }

    @ApiOperation(value = "添加收费模板")
    @RequestMapping(value = "/addChargeTemplate", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "收费模板信息(json字符串)", required = true, dataType = "string", paramType = "form"),
    })
    public R addChargeTemplate(String data) {
        parameterIsBlank(data, "收费模板不能为空");
        JSONObject dataJson = JSONObject.parseObject(data);
        String chargeTemplateName = dataJson.getString("chargeTemplateName");
        String chargeTemplateRemark = dataJson.getString("chargeTemplateRemark");
        Long communityId = dataJson.getLong("communityId");
        JSONArray templateDetailArray = dataJson.getJSONArray("templateDetail");
        if (null == communityId) {
            return R.error(400, "社区id不能为空");
        }
        if (StringUtils.isBlank(chargeTemplateName)) {
            return R.error(400, "模板名称不能为空");
        }
        if (templateDetailArray.isEmpty()) {
            return R.error(400, "模板详情不能为空");
        }
        EstateAgency estateAgency = estateAgencyService.selectById(communityId);
        if (null == estateAgency) {
            return R.error(400, "社区信息错误");
        }
        if(null==estateAgency.getAgencyType()||estateAgency.getAgencyType()!=2){
            return R.error(400,"该机构类型不属于社区");
        }
        ChargeTemplate addTemplate = new ChargeTemplate();
        addTemplate.setCommunityId(communityId).setChargeTemplateName(chargeTemplateName).setChargeTemplateRemark(chargeTemplateRemark)
                .setCreateTime(new Date()).setUpdateTime(addTemplate.getCreateTime());
        addTemplate.setAgencyId(estateAgency.getParentId());
        List<ChargeValue> chargeValueList = new ArrayList<ChargeValue>();
        List<Long> distinctList = new ArrayList<Long>();
        for (int x = 0; x < templateDetailArray.size(); x++) {
            JSONObject templateDetailObj = (JSONObject) templateDetailArray.get(x);
            Long chargeNameId = templateDetailObj.getLong("chargeNameId");
            if (null == chargeNameId) {
                return R.error(400, "chargeNameId不能为空");
            }
            if (distinctList.contains(chargeNameId)) {
                return R.error(400, "收费项请勿重复:" + chargeNameId);
            }
            distinctList.add(chargeNameId);
            double chargeValue = templateDetailObj.getDoubleValue("chargeValue");
            if (chargeValue <= 0) {
                return R.error(400, "单价必选大于0");
            }
            ChargeName oldChargeName = chargeNameService.selectById(chargeNameId);
            if (null == oldChargeName) {
                return R.error(400, "没有该收费项:" + chargeNameId);
            }
            ChargeValue addChargeValue = new ChargeValue();
            addChargeValue.setCommunityId(addTemplate.getCommunityId()).setChargeTemplateId(addTemplate.getChargeTemplateId());
            addChargeValue.setChargeName(oldChargeName.getChargeName()).setChargeNameId(chargeNameId);
            addChargeValue.setChargeType(oldChargeName.getChargeType()).setChargeStartTime(oldChargeName.getChargeStartTime())
                    .setChargeEndTime(oldChargeName.getChargeEndTime()).setChargeWay(oldChargeName.getChargeWay())
                    .setChargeValue(chargeValue).setAgencyId(estateAgency.getParentId());
            chargeValueList.add(addChargeValue);
        }
        addTemplate.setTemplateDetail(chargeValueList);
        chargeTemplateService.addChargeTemplate(addTemplate);
        return R.ok();
    }

    @ApiOperation(value = "修改收费模板")
    @RequestMapping(value = "/editChargeTemplate", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "收费模板信息(json字符串)", required = true, dataType = "string", paramType = "form"),
    })
    public R editChargeTemplate(String data) {
        parameterIsBlank(data, "收费模板不能为空");
        JSONObject dataJson = JSONObject.parseObject(data);
        Long chargeTemplateId = dataJson.getLong("chargeTemplateId");
        if (null == chargeTemplateId) {
            return R.error("收费模板id不能为空");
        }
        String chargeTemplateName = dataJson.getString("chargeTemplateName");
        String chargeTemplateRemark = dataJson.getString("chargeTemplateRemark");
        JSONArray templateDetailArray = dataJson.getJSONArray("templateDetail");
        if (StringUtils.isBlank(chargeTemplateName)) {
            return R.error(400, "模板名称不能为空");
        }
        if (templateDetailArray.isEmpty()) {
            return R.error(400, "模板详情不能为空");
        }
        ChargeTemplate editTemplate = chargeTemplateService.selectById(chargeTemplateId);
        if (null == editTemplate) {
            return R.error(400, "没有该收费模板信息");
        }
        editTemplate.setChargeTemplateName(chargeTemplateName).setChargeTemplateRemark(chargeTemplateRemark).setUpdateTime(new Date());
        List<ChargeValue> chargeValueList = new ArrayList<ChargeValue>();
        List<Long> distinctList = new ArrayList<Long>();
        for (int x = 0; x < templateDetailArray.size(); x++) {
            JSONObject templateDetailObj = (JSONObject) templateDetailArray.get(x);
            Long chargeNameId = templateDetailObj.getLong("chargeNameId");
            if (null == chargeNameId) {
                return R.error(400, "chargeNameId不能为空");
            }
            if (distinctList.contains(chargeNameId)) {
                return R.error(400, "收费项请勿重复:" + chargeNameId);
            }
            distinctList.add(chargeNameId);
            double chargeValue = templateDetailObj.getDoubleValue("chargeValue");
            if (chargeValue <= 0) {
                return R.error(400, "单价必选大于0");
            }
            ChargeName oldChargeName = chargeNameService.selectById(chargeNameId);
            if (null == oldChargeName) {
                return R.error(400, "没有该收费项:" + chargeNameId);
            }
            ChargeValue addChargeValue = new ChargeValue();
            addChargeValue.setCommunityId(editTemplate.getCommunityId()).setChargeTemplateId(editTemplate.getChargeTemplateId());
            addChargeValue.setChargeName(oldChargeName.getChargeName()).setChargeNameId(chargeNameId);
            addChargeValue.setChargeType(oldChargeName.getChargeType()).setChargeStartTime(oldChargeName.getChargeStartTime())
                    .setChargeEndTime(oldChargeName.getChargeEndTime()).setChargeWay(oldChargeName.getChargeWay())
                    .setChargeValue(chargeValue);
            chargeValueList.add(addChargeValue);
        }
        editTemplate.setTemplateDetail(chargeValueList);
        chargeTemplateService.updateChargeTemplate(editTemplate);
        return R.ok();
    }

    @ApiOperation(value = "查询未绑定 物业费模板 的户室")
    @RequestMapping(value = "/readNotTemplateToHouse", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "communityId", value = "社区id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "unitId", value = "单元id", required = false, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "floorId", value = "楼层id", required = false, dataType = "long", paramType = "form"),
    })
    public R readNotTemplateToHouse(Long communityId,Long unitId,Long floorId) {
        parameterIsNull(communityId, "社区id不能为空");
        EstateAgency community = estateAgencyService.selectById(communityId);
        parameterIsNull(community,"没有该社区信息");
        Wrapper<UnitHouse> notTempHouseWp = new EntityWrapper<UnitHouse>().eq("community_id",communityId);
        boolean estateHouseTag = true;
        if(null!=unitId){notTempHouseWp.eq("unit_id",unitId);estateHouseTag=false; }
        if(null!=floorId){notTempHouseWp.eq("floor_Id",floorId);estateHouseTag=false;}
        if(estateHouseTag){ notTempHouseWp.eq("is_estate_house",2);}// 不查询物业办公室
        notTempHouseWp.eq("is_hava_charge_template",2);// 查询 未绑定物业费模板
        notTempHouseWp.orderBy("unit_id",true);
        notTempHouseWp.orderBy("floor_sort",true);
        notTempHouseWp.orderBy("house_sort",true);
        List<UnitHouse> notTempHouse = unitHouseService.selectList(notTempHouseWp);
        if(null==notTempHouse){notTempHouse = new ArrayList<UnitHouse>();}
        return R.ok().put("data", notTempHouse).putDescription(UnitHouse.class);
    }


    @ApiOperation(value = "户室绑定 物业费模板 ")
    @RequestMapping(value = "/bindTemplateToHouse", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "chargeTemplateId", value = "收费模板id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "houseIds", value = "户室id集合/数组", required = true, dataType = "list", paramType = "form"),
    })
    public R bindTemplateToHouse(Long chargeTemplateId,List<Long> houseIds) {
        parameterIsNull(chargeTemplateId, "请选择收费模板");
        if(null==houseIds||houseIds.isEmpty()){return  R.error(400,"请选择要绑定的房间");}
        ChargeTemplate chargeTemplate = chargeTemplateService.selectById(chargeTemplateId);
        parameterIsNull(chargeTemplate, "暂无该收费模板信息");
        List<UnitHouse> unitHouses = unitHouseService.selectList(new EntityWrapper<UnitHouse>().in("house_id",houseIds));
        if(null!=unitHouses&&!unitHouses.isEmpty()){
            for(int x=0;x<unitHouses.size();x++){
                unitHouses.get(x).setChargeTemplateId(chargeTemplateId);
                unitHouses.get(x).setChargeTemplateName(chargeTemplate.getChargeTemplateName());
                unitHouses.get(x).setIsHavaChargeTemplate(1);
            }
            unitHouseService.updateBatchById(unitHouses);
        }
        return R.ok();
    }

}
